/**
 * Created by Administrator on 2017/7/20.
 */


var messageService = require('../messageService');

function SessionManager() {
    this.onlines = {};
}

SessionManager.prototype = {
    userOnline: function(uid, sid) {
        this.onlines[uid] = sid;
    },

    userOffline: function(uid) {
        delete this.onlines[uid];
    },

    isUserOnline: function(uid) {
        return this.onlines[uid];
    },

    getFrontendServerId: function(uid) {
        return this.onlines[uid];
    },

    onlineCount: function() {
        return Object.keys(this.onlines).length;
    },

    sendToUser: function(uid, route, msg) {
        var sid = this.onlines[uid];
        if (sid) {
            messageService.send({uid: uid, sid: sid}, route, msg);
            logger.debug("world uid=%d sid=%j send %s %j", uid, sid, route, msg);
        }
    },

    broadcast: function(uids, route, msg) {
        var sids = [];

        var onlines = this.onlines;
        uids.forEach(function(uid) {
            var sid = onlines[uid];
            if (sid) {
                sids.push({uid:uid, sid:sid});
            }
        });

        if (sids.length > 0) {
            messageService.broadcast(sids, route, msg);
            logger.debug("world broadcast %s %j %j", route, msg, sids);
        }
    },
}

exports.SessionManager = SessionManager;